package com.pengcheng.taskapplication.mvp.view.activity;

import android.content.Context;
import android.content.Intent;
import android.media.session.MediaSession;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.pengcheng.taskapplication.R;
import com.pengcheng.taskapplication.contants.ConstantValue;
import com.pengcheng.taskapplication.model.CheckModel;
import com.pengcheng.taskapplication.model.NewLoginModel;
import com.pengcheng.taskapplication.model.PhoneCodeVo;
import com.pengcheng.taskapplication.model.SubscribeOrderListModel;
import com.pengcheng.taskapplication.model.TokenModel;
import com.pengcheng.taskapplication.model.UserDetailVo;
import com.pengcheng.taskapplication.model.UserTokenModel;
import com.pengcheng.taskapplication.model.UserVo;
import com.pengcheng.taskapplication.mvp.presenter.UserPresenter;
import com.pengcheng.taskapplication.mvp.presenter.UserPresenterV2;
import com.pengcheng.taskapplication.net.IView;
import com.pengcheng.taskapplication.util.Code;
import com.pengcheng.taskapplication.util.PerfectClickListener;
import com.pengcheng.taskapplication.util.SPUtils;
import com.pengcheng.taskapplication.util.ToastUtils;
import com.twitter.sdk.android.core.models.User;

import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Create by xuke on 2017/10/28
 * 验证码登录
 */
public class LoginActivity extends BaseActivity implements IView {
    long  certid;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.btn_check_code)
    TextView btnCheckCode;
    @BindView(R.id.tv_login)
    TextView tv_login;
    @BindView(R.id.iv_showCode)
    ImageView iv_showCode;
    @BindView(R.id.ll_image_code)
    LinearLayout ll_image_code;
    @BindView(R.id.et_password)
    EditText et_password;
    private int count;
    private int page=1;
    private int size=10;
    private UserPresenter userPresenter;
    private UserPresenterV2 userPresenter2;
    private boolean timeEnable = true;
    private String realCode;
    private long from;
    private UserDetailVo userDetailVo;

    @Override
    protected int layoutResID() {
        return R.layout.activity_login;
    }

    @Override
    protected void initData() {
        from =getIntent().getLongExtra("from",1000l);
        userPresenter = new UserPresenter(this);
        userPresenter2=new UserPresenterV2(this);
        setListener();
    }

    private boolean isShowPassword = false;

    /**
     * 设置监听
     */
    private void setListener() {
        //手机号
        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (timeEnable) {
                    boolean enable = !TextUtils.isEmpty(s);
                    btnCheckCode.setEnabled(enable);
                }
            }
        });
        btnCheckCode.setOnClickListener(listener);
        tv_login.setOnClickListener(listener);
        iv_showCode.setOnClickListener(listener);

    }

    private PerfectClickListener listener = new PerfectClickListener() {
        @Override
        protected void onNoDoubleClick(View view) {
            int id = view.getId();
            if (id == R.id.tv_login) {
                String phoneStr = etPhone.getText().toString();
                String code = etCode.getText().toString();
                if (TextUtils.isEmpty(phoneStr)) {
                    etPhone.requestFocus();
                    ToastUtils.showShortToastSafe("请输入手机号");
                    return;
                }
                if (TextUtils.isEmpty(code)) {
                    etCode.requestFocus();
                    ToastUtils.showShortToastSafe("请输入验证码");
                    return;
                }
                if(count>=3){
                    String codeStr= et_password.getText().toString().toLowerCase();
                    if(codeStr==null||codeStr.length()==0||!codeStr.equals(realCode)){
                        ToastUtils.showShortToastSafe("请输入图形验证码");
                        return;
                    }
                }


                //登录
                login();
            }else if(id == R.id.btn_check_code){
                if (isVerPhone()) {
                    //发短信
                    getMessage();
                }
            }else if(id == R.id.iv_showCode){
                //将验证码用图片的形式显示出来
                iv_showCode.setImageBitmap(Code.getInstance().createBitmap());
                realCode = Code.getInstance().getCode().toLowerCase();
            }

        }
    };

    /**
     * 发送短信验证码
     */
    private void getMessage() {
        String cellphone=etPhone.getText().toString().trim();
        userPresenter.getCode(cellphone, ConstantValue.RequestKey.getCode);
    }

    //检查手机号
    private boolean isVerPhone() {
        String phone= etPhone.getText().toString();
        if (phone==null||phone.length()==0||phone.length()!=11) {
            ToastUtils.showShortToastSafe("请检查手机号的格式");
            etPhone.requestFocus();
            return false;
        }
        return true;
    }

    private void login(){
        String username=etPhone.getText().toString();
        String password=etCode.getText().toString();
        UserVo userVo=new UserVo();
        userVo.setCellphone(username);
        userVo.setValidCode(password);
        userPresenter.Login(userVo, ConstantValue.RequestKey.login);
    }



    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    @Override
    public void onSuccess(String code, String msg, Object data, String actionType) {
        if(actionType.equals(ConstantValue.RequestKey.getCode)){
            timeEnable = false;
            btnCheckCode.setEnabled(false);
            CountDownTimer mCountDownTimer = new CountDownTimer(
                    60 * 1000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    long s = millisUntilFinished / 1000;
                    String text = s + "s";
                    btnCheckCode.setText(text);
                }

                @Override
                public void onFinish() {
                    timeEnable = true;
                    btnCheckCode.setText("发送验证码");
                    boolean enable = !TextUtils.isEmpty(etPhone.getText().toString());
                    btnCheckCode.setEnabled(enable);
                    this.cancel();
                }
            };
            mCountDownTimer.start();
        }
        if(actionType.equals(ConstantValue.RequestKey.login)){
            UserTokenModel tokenModel=(UserTokenModel)data;
            SPUtils.put(context,ConstantValue.SpType.token, tokenModel.getToken());
            SPUtils.put(context,ConstantValue.SpType.userid,tokenModel.getMemberId());
            userPresenter2.newLogin(tokenModel.getMemberId().toString(),ConstantValue.RequestKey.newLogin);

        }

        if(actionType.equals(ConstantValue.RequestKey.newLogin)){
            NewLoginModel model=(NewLoginModel) data;
            SPUtils.put(context,ConstantValue.SpType.newtoken,model.getToken());
            getUserDetail();
        }
        if(actionType.equals(ConstantValue.RequestKey.getSubscribes)){
            ArrayList<SubscribeOrderListModel> list= (ArrayList<SubscribeOrderListModel>)data;
            if(list.size()==0){
                Intent intent = new Intent(context, Html5AgressActivity.class);
                intent.putExtra("url","file:///android_asset/instructions.html");
                intent.putExtra("title","办理须知");
                startActivity(intent);
                LoginActivity.this.finish();
            }else{
                Intent intent =new Intent(context,MyApplyAndCarsList.class);
                intent.putExtra("from",0l);
                startActivity(intent);
                LoginActivity.this.finish();
            }
        }

        if(actionType.equals(ConstantValue.RequestKey.userinfo)) {
            //根据来源做跳转
            userDetailVo = (UserDetailVo) data;
            if(userDetailVo!=null){
                SPUtils.put(context,ConstantValue.SpType.phone,userDetailVo.getCellphone());
            }
//            if (from == 0) {
//                if (userDetailVo != null) {
//                    //未实名
//                    if (!userDetailVo.isHasRealNameAuth()) {
//                        Intent intent = new Intent(context, UploadIdCard.class);
//                        intent.putExtra("from", from);
//                        intent.putExtra("flag", 0l);
//                        //intent.putExtra("certId",certid);
//                        startActivity(intent);
//                        LoginActivity.this.finish();
//                    } else {
//                            if (from == 0) {
//                                getSubscribes(page, size);
//                            } else {
//                                //银行列表
//                                Intent intent = new Intent(context, MyBankList.class);
//                                startActivity(intent);
//                                LoginActivity.this.finish();
//                            }
//                       }
//                }
//            }else if(from==2)
//            {
//                //智慧停车
//                Intent intent =new Intent(context,ParkScanActivity.class);
//                startActivity(intent);
//                LoginActivity.this.finish();
//            }else if(from==3){
//                //智慧洗车
//                Intent intent =new Intent(context,ParkWashActivity.class);
//                startActivity(intent);
//                LoginActivity.this.finish();
//
//            } else if(from==4){
//                //智慧洗车
//                Intent intent =new Intent(context,MyInfo.class);
//                startActivity(intent);
//                LoginActivity.this.finish();
//
//            } else if(from==5){
//                Intent intent = new Intent(context, MyApplyAndCarsList.class);
//                intent.putExtra(ConstantValue.IntentKey.KEY_FROM_TYPE, 1);
//                startActivity(intent);
//                LoginActivity.this.finish();
//
//            }else{
//                LoginActivity.this.finish();
//            }
            LoginActivity.this.finish();

        }
    }

    public void checkOcr(){
        userPresenter.checkCert(ConstantValue.RequestKey.checkCert);
    }
    public void getUserDetail(){
        userPresenter.getUserDetail(ConstantValue.RequestKey.userinfo);
    }
    public void getSubscribes(int page,int pageSize){
        userPresenter.getSubscribes(page,pageSize,ConstantValue.RequestKey.getSubscribes);
    }

    @Override
    public void onFailed(String code, String msg) {
        ToastUtils.showShortToast(msg);
        count++;
        if(count>=3){
            ll_image_code.setVisibility(View.VISIBLE);
            //将验证码用图片的形式显示出来
            iv_showCode.setImageBitmap(Code.getInstance().createBitmap());
            realCode = Code.getInstance().getCode().toLowerCase();
        }else{
            ll_image_code.setVisibility(View.GONE);
        }
    }
}
